package ws

import (
	"fmt"
	"log"

	global "github.com/smash-llj/Nexa-server/global"
)

type Hub struct {
	Clients    map[int]*Client
	Register   chan *Client
	Unregister chan *Client
	Broadcast  chan *Message
}

type MemberIds struct {
	UserID int
}

func NewHub() *Hub {
	return &Hub{
		Clients:    make(map[int]*Client),
		Register:   make(chan *Client),
		Unregister: make(chan *Client),
		Broadcast:  make(chan *Message),
	}
}

func (h *Hub) Run() {
	for {
		select {
		case client := <-h.Register:
			h.registerClient(client)
		case client := <-h.Unregister:
			fmt.Println("有人关闭了")
			h.unregisterClient(client)
		case message := <-h.Broadcast:
			h.broadcastHandelMessage(message)
		}
	}
}

// 注册客户端
func (h *Hub) registerClient(client *Client) {
	if _, exists := h.Clients[client.ID]; exists {
		log.Println("删除已经失效的client ID:", client.ID)
		delete(h.Clients, client.ID) // 删除原有的客户端
	}
	h.Clients[client.ID] = client
}

// 删除客户端
func (h *Hub) unregisterClient(client *Client) {
	if _, exists := h.Clients[client.ID]; exists {
		//h.broadcastLeavingMessage(client)
		delete(h.Clients, client.ID)
	}
}

// 广播下线消息
func (h *Hub) broadcastLeavingMessage(client *Client) {
	//message := &Message{
	//	SendID:  client.ID,
	//	Content: fmt.Sprintf("用户%v离开了聊天", "xxx"),
	//}
	//h.Broadcast <- message
}

// 广播消息处理器
func (h *Hub) broadcastHandelMessage(message *Message) {
	switch {
	case message.ChatType == global.ChatTypeGroup:
		h.broadcastToGroup(message)
	case message.ChatType == global.ChatTypeUser:
		h.broadcastToUser(message)
	default:
		h.broadcastToUser(message)
	}
}

// 发送消息
func (h *Hub) sendToClient(userID int, message *Message) {
	if client, exists := h.Clients[userID]; exists {
		client.Message <- message
	}
}

// 广播消息给好友
func (h *Hub) broadcastToUser(message *Message) {
	// 发送消息给接收者
	h.sendToClient(message.ToId, message)
	//h.sendToClient(message.SendID, message)
}

// 广播消息给群
func (h *Hub) broadcastToGroup(message *Message) {
	groupMembers, _ := GetGroupMemberList(message.ToId)
	for _, member := range groupMembers {
		if member != message.SendId {
			h.sendToClient(member, message)
		}
	}
}
